package org.example.tulurouter.interceptor;


import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.tulurouter.common.BaseContext;
import org.example.tulurouter.properties.JwtProperties;
import org.example.tulurouter.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;



/**
 * 校验令牌拦截器
 */
@Component
@Slf4j
public class LoginTokenintercepter implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到了请求:{}",request.getRequestURI());
        //1.获取请求头中的令牌
        String jwt = "";
        //1.1 如果是 OPTIONS 请求，我们就让他通过，不管他
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            log.info("OPTIONS请求！");
            return true;
            //1.2 如果不是，我们就把token拿到，用来做判断
        }else {
           jwt = request.getHeader("Authorization");
        }

        //2.判断令牌是否存在，如果不存在，则报401
        if (!StringUtils.hasLength(jwt)){
            log.info("令牌为空");
            response.setStatus(401);
            return false;
        }
        //3.校验令牌
        try {
            JwtUtil.parseJWT(jwtProperties.getAdminSecretkey(),jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌非法");
            response.setStatus(401);
            return false;
        }
        //4.存取id到threadLocal
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretkey(),jwt);
        Long id = claims.get("id",Long.class);
        BaseContext.setCurrentId(id);

        //4.放行
        return true;
    }
}
